﻿using Bootstrap.Definition.Enums;
using Bootstrap.Definition.Events;
using Bootstrap.Helper;
using Bootstrap.Template.TemplateInnerItem;
using Bootstrap.Template.Textbox;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Bootstrap.Control
{
   
    [ToolboxData("<{0}:BootstrapTextbox runat=server></{0}:BootstrapTextbox>")]
    public class BootstrapTextbox : WebControl, IPostBackDataHandler
    {
        #region Properties
        
        public string Text { get; set; }

        public string LeftAddonText { get; set; }

        public string RightAddonText { get; set; }

        public string PlaceHolderText { get; set; }

        public SizeEnum Size { get; set; }

        public string CustomStyle { get; set; }

        public event EventHandler OnTextChanged;

        #endregion

        #region Methods

        protected override void Render(HtmlTextWriter writer)
        {
            BootstrapTextboxTemplateItem templateItem = new BootstrapTextboxTemplateItem();

            templateItem.LeftAddonText = ValueHelper.GetDefaultValue<string>(this.LeftAddonText, string.Empty);
            templateItem.RightAddonText = ValueHelper.GetDefaultValue<string>(this.RightAddonText, string.Empty);
            templateItem.PlaceHolderText = ValueHelper.GetDefaultValue<string>(this.PlaceHolderText, string.Empty);
            templateItem.Text = ValueHelper.GetDefaultValue<string>(this.Text, string.Empty);
            templateItem.Width = ValueHelper.GetDefaultValue<double>(this.Width.Value, 100) + "px";
            templateItem.Style = ValueHelper.GetDefaultValue<string>(this.CustomStyle, string.Empty);
            templateItem.ClientID = ValueHelper.GetDefaultValue<string>(this.UniqueID, string.Empty);
            templateItem.Size = Size;

            BootstrapTextboxTemplate template = new BootstrapTextboxTemplate(templateItem);

            writer.Write(template.TransformText());

            base.Render(writer);
        }

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            var data = postCollection[postDataKey];

            if (data != null)
            {
                this.Text = data;

                return true;
            }

            return false;
        }

        public void RaisePostDataChangedEvent()
        {
            if (OnTextChanged != null)
            {
                var eventArgs = new TextChangedEventArgs() { Text = this.Text };

                OnTextChanged(this, eventArgs);

                if (eventArgs.Text != null)
                {
                    this.Text = eventArgs.Text;
                }
            }
        }

        #endregion
    }

}
